'use strict';

app.controller('incidentListCtrl', ["$scope", "i18nService", "$rootScope", "$state", "$timeout", "$interval", "$modal", "SweetAlert", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm_domain", function($scope, i18nService, $rootScope, $state, $timeout, $interval, $modal, SweetAlert, uiGridConstants, uiGridGroupingConstants, Restangular, api_bpm_domain) {
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);

    var loginUser = $rootScope.user;
    $scope.allright = false;
    $scope.allrightnot = true;
    for (var obj in $rootScope.user.role) {
        if ($rootScope.user.role[obj].rolecode == 'incident manager') {
            $scope.allright = true;
            $scope.allrightnot = false;
        }
    }
    var pdKey = $state.current.pdKey;

    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = true;
    $scope.gridOptions.enableGridMenu = false;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = true;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalFiltering = true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;


    $scope.gridOptions.rowTemplate = "<div ng-dblclick=\"grid.appScope.pdList.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    $scope.gridOptions.columnDefs = [
        { name: '操作', cellTemplate: '<incidentoperator item="row.entity" colobject="col">', width: 100, enableFiltering: false },
        { name: 'incidentsign', displayName: '事件单号', width: 80 },
        { name: 'title', displayName: '事件标题', width: 140 },
        { name: 'requester.name', displayName: '请求人', width: 100, enableFiltering: false },
        { name: 'acceptDate', displayName: '登记时间', width: 120, enableFiltering: false },
        { name: 'source.source', displayName: '事件来源', width: 100, enableFiltering: false },
        { name: 'type.name', displayName: '事件类型', width: 100, enableFiltering: false },
        { name: 'category.category', displayName: '事件分类', width: 100, enableFiltering: false },
        { name: 'reCategory.recate', displayName: '服务目录', width: 100, enableFiltering: false },
        { name: 'priority.name', displayName: '优先级', width: 80, enableFiltering: false },
        { name: 'state.name', displayName: '状态', width: 80, enableFiltering: false }
        //'<div class="links cl-effect-1">' +
        //      '<a ng-click="grid.appScope.selectRowFunction(row.entity)" tooltip="编辑" tooltip-placement="left"><i class="fa fa-pencil-square-o"></i></a>'+
        //      '</div>' , width:100, enableFiltering:false}
    ];


    $scope.refresh = function(style, filterData) {
        var filtersData = {
            "assignee": $rootScope.user.id,
            "candidateGroups": $rootScope.user.group[0].id,
            idx: 0,
            sum: 10
        };
        $scope.gridOptions.refresh();
        $scope.refreshData('expand-right', filtersData);
    };


    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            var filtersData = $scope.memoryfilterData;
            filtersData.idx = newPage - 1;
            filtersData.sum = pageSize;
            $rootScope['idx'] = newPage;
            $scope.refreshData('expand-right', filtersData);
            // $scope.refreshData('expand-right', {"assignee":$rootScope.user.id, "candidateGroups":$rootScope.user.group[0].id, "idx":newPage-1,"sum":pageSize});                                            
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
            //$scope.selected.item = data.entity;
            // console.log(data);
        });
        gridApi.core.on.filterChanged($scope, function() {
            var grid = this.grid;
            var filtersData = {
                "assignee": $rootScope.user.id,
                "candidateGroups": $rootScope.user.group[0].id,
                idx: 0,
                sum: 10
            };
            angular.forEach(grid.columns, function(item) {
                if (item.enableFiltering) {
                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                        // console.log('item.filters[0]='+JSON.stringify(item.filters[0]));
                        if (angular.isUndefined(filtersData['incident'])) {
                            filtersData['incident'] = {};
                        }
                        filtersData['incident'][item.field] = item.filters[0].term;
                    }
                }
            });
            $scope.memoryfilterData = filtersData;
            $scope.refreshData('expand-right', filtersData);
        });
    };
    $scope.memoryfilterData = defaultFilterData = {
        "assignee": $rootScope.user.id,
        "candidateGroups": $rootScope.user.group[0].id,
        "idx": 0,
        "sum": 10
    };

    $scope.selectRowFunction = function(data) {
        $state.go('app.incident.editor', { taskId: data.taskId, processInstanceId: data.processInstanceId });

    };
    $scope.lookFunction = function(data) {
        // console.log('data='+JSON.stringify(data));
        //$state.go('app.detail',{taskId:data.taskId,processInstanceId: data.processInstanceId});
        $state.go('app.detail', { formKey: 'incident_back', pdKey: 'incident', dataId: data.id, taskId: data.taskId, processInstanceId: data.processInstanceId });
    };

    // $scope.onDblClick = function(data) {
    //     $state.go('app.detail', { formKey: 'incident_back', pdKey: 'incident', dataId: data.id, taskId: data.taskId, processInstanceId: data.processInstanceId });
    // };
    $scope.onDblClick = function(row) {
        //console.log(row.entity);
        $state.go('app.detail', { formKey: 'incident_back', pdKey: 'incident', dataId: row.entity.id, taskId: row.entity.taskId, processInstanceId: row.entity.processInstanceId });
    };

    /*
      appScopeProvider: { 
          onDblClick : function(row) {
             var url = '//google.com';
             $window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
           }
      },
      rowTemplate: "<div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" ui-grid-cell ></div>"

     */
    $scope.eventDeleted = function(event) {
        SweetAlert.swal({
            title: "确认删除?",
            text: "删除的数据不可恢复，请确认继续操作!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "继续删除",
            cancelButtonText: "取消操作",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {
                api_bpm_schedule.remove([event.id]).then(function(response) {
                    if (response.status == 200) {
                        $scope.events.splice(event.id, 1); //有修改的一行
                        SweetAlert.swal("操作成功!", "数据已经被删除.", "success");
                    } else {
                        SweetAlert.swal("操作失败!", "数据暂时无法被删除,请稍候重试", "error");
                    }
                });
            } else {
                SweetAlert.swal("操作取消", "数据安全", "error");
            }
        });
    };


    $scope.acceptTaskAction = function(model) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/incident/tpl/acceptTask.tpl.html',
            controller: function($scope, $modalInstance, APIService, modelData, currentUserId, Alert) {
                var receiveTask = function(receive_code, modelData) {
                    var data = {
                        'receive_code': receive_code
                    };

                    if (modelData) {
                        return {
                            taskId: modelData.taskId,
                            data: data
                        };
                    } else {
                        return 'error';
                    }
                };

                $scope.ok = function() {
                    //接收任务//请求重新指派
                    var data = receiveTask($scope.receive_code, modelData);
                    APIService.claimtask(data.taskId, { userId: currentUserId }).then(function(response) {
                        if (response.status == 200) {
                            Alert.swal({
                                title: "操作成功!",
                                confirmButtonColor: "#007AFF",
                                type: "success"
                            });
                            $modalInstance.close('success');
                        } else if (response.status == 500) {
                            Alert.swal({
                                title: "操作失败",
                                text: "该事件已被提取，请刷新页面!",
                                type: "error"
                            });
                            $modalInstance.close('success');
                        } else {
                            Alert.swal({
                                title: "操作失败",
                                text: "操作失败, 请稍后再试!",
                                type: "error"
                            });
                        }
                    });
                }

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                }
            },
            size: 'sm',
            resolve: {
                APIService: function() {
                    return api_bpm_domain;
                },
                modelData: function() {
                    return model;
                },
                currentUserId: function() {
                    return loginUser.id;
                },
                Alert: function() {
                    return SweetAlert;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem == 'success') {
                $scope.refreshData('expand-right', defaultFilterData);
            }
        });
    }


    //$scope.callsPending = 0;
    //var i = 0;
    var defaultFilterData = {
        "assignee": $rootScope.user.id,
        "candidateGroups": $rootScope.user.group[0].id,
        "idx": 0,
        "sum": 10
    };
    if (angular.isDefined($rootScope.search) && angular.isDefined($rootScope.search.incident)) {
        defaultFilterData['searchType'] = $rootScope.search.incident;
        $scope.searchTypes = $rootScope.search.incident;
    }
    if ($rootScope['cmdbs'] != 'incident') { $rootScope.idx = 1 }
    if (angular.isDefined($rootScope.idx) && $rootScope.cmdbs != "false") {
        $rootScope['cmdbs'] = 'incident';
        defaultFilterData.idx = $rootScope.idx - 1;
    } else { $rootScope.cmdbs = ""; }
    $scope.ldloading = {};

    $scope.refreshData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            // $scope.gridOptions.onRegisterApi = function(gridApi){
            //     $scope.gridApi = gridApi;
            //     gridApi.core.on.filterChanged($scope, function() {
            //       var grid = this.grid;
            //       var filtersData = {
            //         "assignee":$rootScope.user.id,
            //         "candidateGroups":$rootScope.user.group[0].id,
            //         idx:0,
            //         sum:10
            //       };
            //       $scope.refreshData('expand-right', filtersData);
            //     });
            //   };
            // defaultFilterData.idx=$rootScope.idx-1;
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            $rootScope['search'] = {};
            filterData['searchType'] = $scope.searchTypes;
            $rootScope['search']['incident'] = $scope.searchTypes;
        }
        $scope.myData = [];
        api_bpm_domain.fetchtask(pdKey, filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.resultCount;
            $scope.myData = myData.data;
            $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });
    };

    $scope.refreshData('expand-right', defaultFilterData);
}]);

app.controller('IncidentOperCtrl', ['$rootScope', '$http', '$scope', function($rootScope, $http, $scope, $event) {
    // console.log('$rootScope.user3='+JSON.stringify($scope.item));
    if ($scope.item.state.id != 6 && $scope.item.handlerUser != null) {

        if ($rootScope.user.id == $scope.item.handlerUser.id) {
            $scope.item.chaozuoPower = true;

        }
    }
    if ($scope.item.state.id != 6 && $scope.item.handlerUser == null) {
        //  console.log('$rootScope.user4='+JSON.stringify($rootScope.nickname));
        //if ($rootScope.user.nickname==$rootScope.nickname) {
        $scope.item.tiquPower = true;

        //console.log('$rootScope.user='+JSON.stringify($rootScope.user)); 

    }
    // console.log('$scope.item.actions='+JSON.stringify($scope.item.actions));                   
    // if($scope.item.actions!=""&&$scope.item.actions!=null){//1:提取，2:操作(改)；
    //    console.log('$rootScope.user2='+JSON.stringify($rootScope.user));
    //     if($scope.item.actions.indexOf("1")>=0){//提取
    //         $scope.item.detailPower=true;
    //     }
    //     if($scope.item.actions.indexOf("2")>=0||$rootScope.user.id==1){//操作(改)
    //         $scope.item.updatePower=true;
    //     }

    // }
    // if($scope.item.status==3){//已发布的才能评论
    //     $scope.item.commontPower=true;
    // }else{
    //     $scope.item.commontPower=false;
    // }
    $scope.look = function() {
        //$state.go('app.detail', { formKey:'incident_back', pdKey:'incident', dataId: $scope.item.id});
        $scope.colobject.grid.appScope.lookFunction($scope.item);
        // console.log('$scope.item='+JSON.stringify($scope.item));
        //$scope.doEdit($scope.item.id);
    }
    $scope.edit = function() {
        $scope.colobject.grid.appScope.selectRowFunction($scope.item);
        // console.log('$scope.item='+JSON.stringify($scope.item));
        $scope.doEdit($scope.item.id);
    }

    $scope.handler = function() {
        $scope.colobject.grid.appScope.acceptTaskAction($scope.item);
        $scope.doComment($scope.item.id);
    }

}]);

app.directive('incidentoperator', function() {
    return {
        restrict: 'E',
        scope: {
            item: '=',
            colobject: '='
        },
        controller: 'IncidentOperCtrl',
        template: '<div class="links cl-effect-1 ui-grid-cell-contents">' +
            '<a ng-click="look()"   tooltip="查看" tooltip-placement="right"><i class="ti-eye"></i></a>' +
            '<a ng-click="edit()"  ng-show="{{item.chaozuoPower}}" tooltip="编辑" tooltip-placement="right"><i class="fa fa-pencil-square-o"></i></a>' +
            '<a ng-click="handler()" ng-show="{{item.tiquPower}}" tooltip="提取" tooltip-placement="right"><i class="fa fa-pencil"></i></a>' +
            '</div>'
    };
});